package it.unibo.convoycruisecontrol.boatsubsystem.presentation.swing;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.NumberFormat;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;
import javax.swing.JTextArea;

import it.unibo.convoycruisecontrol.boatsubsystem.ObservableDashboard;
import it.unibo.location.ILocation;
import it.unibo.util.measures.*;

public class DashboardView extends JPanel implements Observer
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JTextArea informations = null;
	private JTextArea positions = null;
	private ObservableDashboard dashboard = null;

	public DashboardView(ObservableDashboard dashboard)
	{
		this.dashboard = dashboard;

		dashboard.addObserver(this);
		initGui();
	}

	protected void initGui()
	{
		setLayout(new FlowLayout());

		informations = new JTextArea();
		informations.setEditable(false);
		informations.setPreferredSize(new Dimension(340,100));
		
		positions = new JTextArea();
		positions.setEditable(false);
		positions.setPreferredSize(new Dimension(320,150));
	
		add(informations);
		add(positions);
		
		setVisible(true);
	}

	private String createInformationsString(float speed, float distance)
	{
		NumberFormat formatter = NumberFormat.getInstance();
		formatter.setMaximumFractionDigits(1);
		StringBuilder builder = new StringBuilder();
		builder.append("Current Speed:\n");
		builder.append("\t in kn:");
		builder.append(formatter.format(MetersSecondToKnots.convert(speed)));
		builder.append("\t in km/sec:");
		formatter.setMaximumFractionDigits(3);
		builder.append(formatter.format(MetersSecondToKilometersSecond.convert(speed)));
		builder.append("\n\n");
		builder.append("Distance covered:\n");
		builder.append("\t in km:");
		builder.append(formatter.format(MetersToKilometers.convert(distance)));
		builder.append("\t in Nm:");
		builder.append(formatter.format(MetersToNauticalMiles.convert(distance)));

		return builder.toString();
	}

	private String createPositionsString(List<ILocation> locations)
	{
		StringBuilder builder = new StringBuilder();
		builder.append("Positions\n");
		for(int i = 0; i < locations.size(); i++)
		{
			builder.append("\nBoat " + i + ": ");
			builder.append(locations.get(i).toString());
		}

		return builder.toString();
	}

	@Override
	public void update(Observable o, Object arg) 
	{
		informations.setText(createInformationsString(dashboard.getDisplayedCurrentSpeed(), dashboard.getDisplayedDistanceCovered()));
		positions.setText(createPositionsString(dashboard.getDisplayedLocations()));
	}
}
